<template>
  <div>
    <el-tabs
      v-model="editableTabsValue"
      type="card"
      closable
      @tab-remove="removeTab"
      @tab-click="clickTab"
    >
      <el-tab-pane
        v-for="item in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
      >{{item.content}}</el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  computed: {
    //当前激活的选项卡
    editableTabsValue: {
      get() {
        return this.$store.state.MenuStore.editableTabsValue;
      },
      set(val) {
        this.$store.state.MenuStore.editableTabsValue = val;
      },
    },
    //选项卡数据
    editableTabs: {
      get() {
        return this.$store.state.MenuStore.editableTabs;
      },
      set(val) {
        this.$store.state.MenuStore.editableTabs = val;
      },
    },
  },
  methods: {
    removeTab(targetName) {
      //首页禁止关闭
      if (targetName === "Home") {
        return;
      }
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter((tab) => tab.name !== targetName);
      //暂存选项卡
      sessionStorage.setItem("tabsList", JSON.stringify(this.editableTabs));
      //设置当前激活的选项卡
      this.$store.commit("setActiveTabs", this.editableTabsValue);
      //设置路由
      this.$router.push({ name: this.editableTabsValue });
    },
    clickTab(tab) {
      let obj = {};
      if (tab.name === "Home") {
        obj.label = "首页";
      } else {
        obj.label = tab.label;
      }
      obj.name = tab.name;
      this.$store.commit("selectMenu", obj);
      this.$router.push({ name: tab.name });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>